<!-- 网络配置 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0">
      <div style="display: flex; justify-content: space-between">
        <div>
          <div class="btn topSubmitBtn" style="width: 850px">
            <el-button type="primary" @click="submit()">保存设置</el-button>
          </div>
          <el-col :xs="24" :sm="24" :lg="24">
            <div class="parameType">
              <div class="title">有线网络接口参数配置<span style="color:red">{{networkForm.eth0_activated === 0 ? '（配置不生效,请修改后重启保存）' : ''}}</span></div>
              <el-form label-width="120px">
                <el-row>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="设备地址:">
                      <el-input
                        v-model="networkForm.eth0_ip"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="15"
                        placeholder="请输入设备地址"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="8">
                    <el-form-item label="掩码位数:">
                      <el-input
                        v-model.number="networkForm.eth0_mask"
                        oninput="value=value.replace(/[^0-9]/g,'')"
                        maxlength="15"
                        ><span slot="append">默认24位</span></el-input
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="网关地址:">
                      <el-input
                        v-model="networkForm.gateway"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="15"
                        :placeholder="networkForm.wifi_gateway !== '' ? '只能指定一个网关地址' : '请输入网关地址'"
                        :disabled="networkForm.wifi_gateway !== ''"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="主DNS:">
                      <el-input
                        v-model="networkForm.dns_first"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="15"
                        placeholder="请输入主DNS"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="从DNS:">
                      <el-input
                        v-model="networkForm.dns_second"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="15"
                        placeholder="请输入从DNS"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="4" :lg="4" class="r-button">
                    <el-button type="success" @click="CheckInternetByEth0()">连通检测</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-col>
          <el-col :xs="24" :sm="14" :lg="24">
            <div class="parameType">
              <div class="title">无线网络接口参数配置<span style="color:red">{{networkForm.eth0_activated === 0 &&  networkForm.is_wifi === 1 ? '（配置不生效,请修改后重启保存）' : ''}}</span></div>
              <el-form label-width="140px">
                <el-row>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="无线接口：">
                      <el-radio-group v-model.number="networkForm.is_wifi">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="无线路由器选择：">
                      <el-select
                        placeholder="请选择或手动输入"
                        filterable
                        allow-create
                        default-first-option
                        v-model="networkForm.SSID"
                        clearable
                        style="width: 100%"
                        :disabled="networkForm.is_wifi === 0"
                      >
                        <el-option
                          v-for="(item, index) in SsidList"
                          :key="index"
                          :label="item"
                          :value="item"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :lg="6" class="r-button">
                    <el-button
                      style="width:98px;"
                      type="success"
                      @click="SearchWIFIAp()"
                      :disabled="networkForm.is_wifi === 0"
                      >搜索</el-button>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="接入密码：">
                      <el-input
                        v-model="networkForm.Pwd"
                        :disabled="networkForm.is_wifi === 0"
                        oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')"
                        maxlength="32"
                        placeholder="请输入接入密码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="认证方式：">
                      <el-select
                        :disabled="networkForm.is_wifi === 0"
                        v-model="networkForm.AuthType"
                        style="width: 100%"
                      >
                        <el-option label="WPA-PAK" value="WPA-PAK"></el-option>
                        <el-option label="other" value="other"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="指定无线接口地址:">
                      <el-input
                        v-model="networkForm.wifi_ip"
                        :disabled="networkForm.is_wifi === 0"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        maxlength="15"
                        placeholder="请输入无线接口地址"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="8" :lg="8">
                    <el-form-item label="掩码位数：" label-width="120px">
                      <el-input
                        v-model.number="networkForm.wifi_mask"
                        :disabled="networkForm.is_wifi === 0"
                        ><span slot="append">默认24位</span></el-input
                      >
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="14" :lg="14">
                    <el-form-item label="网关地址：">
                      <el-input
                        v-model="networkForm.wifi_gateway"
                        :disabled="networkForm.is_wifi === 0 || networkForm.gateway !== ''"
                        oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')"
                        maxlength="32"
                        :placeholder="networkForm.is_wifi === 0 || networkForm.gateway !== '' ? '只能指定一个网关地址' : '请输入网关地址'"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="4" :lg="4" class="r-button">
                    <el-button
                      type="success"
                      @click="CheckInternetByWifi()"
                      :disabled="networkForm.is_wifi === 0"
                      >连通检测</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </el-col>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
import { hideScreenLoading } from "@/utils/loading";
import { connrequest } from "@/api/firstPage";
export default {
  data() {
    return {
      networkForm: {
        eth0_ip: '',
        eth0_mask: '',
        gateway: '',
        dns_first: '',
        dns_second: '',
        is_wifi: '',
        SSID: '',
        Pwd: '',
        AuthType: '',
        wifi_ip: '',
        wifi_mask: '',
        wifi_gateway: '',
      },
      SsidList: [],
      state: "",
      timer: null
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData();
    // this.SearchWIFIAp()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  beforeDestroy() {
    // window.clearTimeout(this.timer)
  },
  methods: {
    async getData() {
      const res = await connrequest("GetParamInterface");
      this.networkForm = { ...res.Data };
      this.oldIp = res.Data.eth0_ip
      this.oldWifiIp = res.Data.wifi_ip
    },
    async CheckInternetByEth0() {
      const res = await connrequest("CheckInternetByEth0");
      if (res.Status.StatusCode === 0) {
        this.$message.success("有线连通正常");
      }
    },
    async CheckInternetByWifi() {
      const res = await connrequest("CheckInternetByWifi");
      if (res.Status.StatusCode === 0) {
        this.$message.success("无线连通性正常");
      }
    },
    async SearchWIFIAp() {
      const res = await connrequest("SearchWIFIAp");
      let arr = [];
      res.Data = res.Data || []
      res.Data.map((item) => {
        arr.push(item.SSID);
      });
      this.SsidList = arr;
      if(this.SsidList.length > 0) {
        this.$message.success('搜索成功，请选择无线路由器。')
        this.$set(this.networkForm, 'SSID', this.SsidList[0])
      }
    },
    async submit() {
      let ipAddress = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      let subWebMask = /^[0-9]*$/;
      if (!ipAddress.test(this.networkForm.eth0_ip)) {
        this.$message.error("请输入正确的设备地址");
      } else if (!subWebMask.test(this.networkForm.eth0_mask)) {
        this.$message.error("请输入正确的掩码位数");
      } else if (!ipAddress.test(this.networkForm.gateway) && this.networkForm.gateway !== "") {
        this.$message.error("请输入正确的网关地址");
      } else if (!this.networkForm.dns_first) {
        this.$message.error("主DNS不能为空");
      } else if (!this.networkForm.dns_second) {
        this.$message.error("从DNS不能为空");
      } else if (!ipAddress.test(this.networkForm.dns_first) && this.networkForm.dns_first !== "") {
        this.$message.error("请输入正确的主DNS");
      } else if (!ipAddress.test(this.networkForm.dns_second) && this.networkForm.dns_second !== "") {
        this.$message.error("请输入正确的从DNS");
      } else if (this.networkForm.is_wifi === 1 && this.networkForm.SSID === '') {
        this.$message.error("请选择无线路由");
      } else if (this.networkForm.is_wifi === 1 && this.networkForm.Pwd === "") {
        this.$message.error("接入密码不能为空");
      } else if (this.networkForm.is_wifi === 1 && this.networkForm.wifi_ip === "") {
        this.$message.error("无线接口地址不能为空");
      } else if (this.networkForm.is_wifi === 1 && !ipAddress.test(this.networkForm.wifi_ip) && this.networkForm.wifi_ip !== "") {
        this.$message.error("请输入正确的无线接口地址");
      } else if (!ipAddress.test(this.networkForm.wifi_gateway) && this.networkForm.wifi_gateway !== "") {
        this.$message.error("请输入正确的无线网关地址");
      } else if (this.networkForm.is_wifi === 1 && this.networkForm.dns_first === "") {
        this.$message.error("主DNS不能为空");
      } else if (this.networkForm.is_wifi === 1 && this.networkForm.dns_second === "") {
        this.$message.error("从DNS不能为空");
      } else if (this.networkForm.gateway !== "" && this.networkForm.wifi_gateway !== "") {
        this.$message.error("只能指定一个网关地址");
      } else if (this.oldIp !== this.networkForm.eth0_ip || this.oldWifiIp !== this.networkForm.wifi_ip) {
        this.$confirm("提示", {
          message: '检测到设备地址或无线接口地址已经改变, 保存后旧设备地址将不可用, 请使用新地址重新登录',
          confirmButtonText: "保存",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.networkForm.eth0_mask = this.networkForm.eth0_mask === "" ? 24 : this.networkForm.eth0_mask;
          this.networkForm.wifi_mask = this.networkForm.wifi_mask === "" && this.networkForm.is_wifi === 1 ? 24 : this.networkForm.wifi_mask;
          const data = {
            Data: {
              ...this.networkForm,
            },
          };
          connrequest("SetParamInterface", data);
            this.$store.dispatch('user/logout')
            this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            this.timer = setTimeout(()=>{
              window.open("http://" + this.networkForm.eth0_ip,"_self").close() 
            },3000)
        });
      }else {
        this.networkForm.eth0_mask = this.networkForm.eth0_mask === "" ? 24 : this.networkForm.eth0_mask;
        this.networkForm.wifi_mask = this.networkForm.wifi_mask === "" && this.networkForm.is_wifi === 1 ? 24 : this.networkForm.wifi_mask;
        const data = {
          Data: {
            ...this.networkForm,
          },
        };
        const res = await connrequest("SetParamInterface", data);
        if (res.Status.StatusCode === 0) {
          this.$message.success("保存成功");
          this.getData();
        }
        // if (res.Status.StatusCode === 0) {
        //   const confirmText = [
        //     `参数配置保存成功，需要重启设备才能生效。`,
        //     `您需要立刻重启设备吗？(设备重启将导致导致域名加速功能短时间失效)`,
        //   ];
        //   const newDatas = [];
        //   const h = this.$createElement;
        //   for (const i in confirmText) {
        //     newDatas.push(h("p", null, confirmText[i]));
        //   }
        //   this.$confirm("提示", {
        //     message: h("div", null, newDatas),
        //     confirmButtonText: "重启设备",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(async () => {
        //     const data = {
        //       Data: {
        //         Action: "Reboot",
        //       },
        //     };
        //     await connrequest("ExecDeviceMaint", data);
        //     this.$store.dispatch("user/resetToken").then(() => {
        //       location.reload();
        //     });
        //   });
        // }
      }
    }
  }
};
</script>
<style lang="scss"scoped>
.parameType {
  width: 850px;
  margin: 10px 0;
}
.el-form {
  margin-top: 30px;
  .r-button {
    margin-left: 30px;
  }
}
::v-deep.el-form-item {
  label {
    font-weight: 500;
  }
}
</style>